import React, { useEffect } from 'react';
import { Button, Form, Input ,Card, Space, message} from 'antd';
import {reqAddHospitalSet,reqGetOneHospitalSet,reqEditOneHospitalSet,reqDelOneHospitalSet} from '@api/hospitalSet/index'
import { useNavigate ,useParams} from 'react-router-dom';

export default function AddHos() {
  const navigate=useNavigate()
  //路由传参
  const {id} = useParams()
  //form实例  form实例再与Form标签绑定
  const [form] =Form.useForm()
  //保存完成触发
  const onFinish = async(values: any) => {
    if(id){
        //修改时要给服务器上传id
        values.id=id
        console.log(values)
       await reqEditOneHospitalSet(values)
       console.log('返回值' ,values)
       message.success('修改医院成功')
    }else{
        await reqAddHospitalSet(values)
        message.success('添加医院成功')
    }
   navigate(-1)
  };
   //取消
   const clearItem =() =>{
    navigate(-1)
}
//挂载的时候获取修改页面数据
useEffect(() =>{
    if(!id) return 
    (async()=>{
      const result=  await reqGetOneHospitalSet(id as string)
      //form方法，获取数据并渲染到页面
       form.setFieldsValue(result) 
    })()
   
},[])
  
  return (
    <Card>
      <Form form={form}
        name="basic"
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 22 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: 'Please input your hosname!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: 'Please input your hoscode!' }]}
        >
          <Input/>
        </Form.Item>
        <Form.Item
          label="api路径"
          name="apiUrl"
          rules={[{ required: true, message: 'Please input your apiUrl!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="联系人名称"
          name="contactsName"
          rules={[{ required: true, message: 'Please input your contactsName!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="联系人电话"
          name="contactsPhone"
          rules={[{ required: true, message: 'Please input your contactsPhone!' },{pattern:/^1[3,9]\d{9}$/ ,message:'Please input your  right contactsPhone!'}]}
        >
          <Input />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Space>
            <Button type="primary" htmlType="submit">
            保存
          </Button>
          <Button  htmlType="submit" onClick={clearItem}>
            取消
          </Button>
            </Space>
        
        </Form.Item>
      </Form>
    </Card>
  );
}
